package com.mooco.dongba.sys.service.impl;

import com.mooco.dongba.common.exception.ServiceException;
import com.mooco.dongba.common.pojo.Node;
import com.mooco.dongba.sys.dao.SysMenuDao;
import com.mooco.dongba.sys.dao.SysRoleMenuDao;
import com.mooco.dongba.sys.dao.SysUserRoleDao;
import com.mooco.dongba.sys.pojo.SysMenu;
import com.mooco.dongba.sys.pojo.SysUserMenu;
import com.mooco.dongba.sys.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.IllegalFormatException;
import java.util.List;
import java.util.Map;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    @Autowired
    private SysMenuDao sysMenuDao;

    @Override
    public List<SysUserMenu> findUserMenusByUserId(Integer userId) {
        List<Integer> roleIds = sysUserRoleDao.findRoleIdsByUserId(userId);
        List<Integer> menuIds = sysRoleMenuDao.findMenuIdsByRoleIds(roleIds);
        return sysMenuDao.findUserMenusByIds(menuIds);
    }

    @Override
    public List<Map<String, Object>> findObjects() {
        List<Map<String, Object>> list = sysMenuDao.findObjects();
        if (list == null || list.size() == 0) {
            throw new ServiceException("没有对应的菜单信息");
        }
        return list;
    }

    @Override
    public int deleteObject(Integer id) {
        // 数据校验
        if (id == null || id == 0) {
            throw new IllegalArgumentException("请先选择");
        }
        // 1、先查看是否有二级菜单。如果有，则不允许删除；否则，继续下一步
        int count = sysMenuDao.getChildCount(id);
        if (count > 0) {
            throw new ServiceException("请先删除子菜单");
        }
        // 2、删除角色菜单关系
        sysRoleMenuDao.deleteObjectByMenuId(id);
        // 3、删除菜单信息
        int rows = sysMenuDao.deleteObject(id);
        if (rows == 0) throw new ServiceException("此菜单可能已经不存在");
        return rows;
    }

    @Override
    public List<Node> findZTreeMenuNodes() {
        return sysMenuDao.findZTreeMenuNodes();
    }

    @Override
    public int insertObject(SysMenu entity) {
        if (entity == null) throw new IllegalArgumentException("保存对象不能为空");
        if (entity.getName() == null || "".equals(entity.getName()))
            throw new IllegalArgumentException("菜单名不能为空");
        int rows = sysMenuDao.insertObject(entity);
        return rows;
    }

    @Override
    public int updateObject(SysMenu entity) {
        if (entity == null) throw new IllegalArgumentException("保存对象不能为空");
        if (entity.getName() == null || "".equals(entity.getName()))
            throw new IllegalArgumentException("菜单名称不能为空");
        int rows = sysMenuDao.updateObject(entity);
        if (rows == 0) throw new ServiceException("记录可能已经不存在");
        return rows;
    }
}
